package com.chinaunicom.emergency.security;


import lombok.extern.log4j.Log4j2;
import org.springframework.security.crypto.bcrypt.BCrypt;

import java.security.SecureRandom;
import java.util.regex.Pattern;

@Log4j2
public class BCryptPasswordEncoder  {
    private Pattern BCRYPT_PATTERN;
    private final int strength;
    private final SecureRandom random;

    public BCryptPasswordEncoder() {
        this(-1);
    }

    public BCryptPasswordEncoder(int strength) {
        this(strength, (SecureRandom)null);
    }

    public BCryptPasswordEncoder(int strength, SecureRandom random) {
        this.BCRYPT_PATTERN = Pattern.compile("\\A\\$2a?\\$\\d\\d\\$[./0-9A-Za-z]{53}");
        if(strength == -1 || strength >= 4 && strength <= 31) {
            this.strength = strength;
            this.random = random;
        } else {
            throw new IllegalArgumentException("Bad strength");
        }
    }

    public String encode(CharSequence rawPassword) {
        String salt;
        if(this.strength > 0) {
            if(this.random != null) {
                salt = BCrypt.gensalt(this.strength, this.random);
            } else {
                salt = BCrypt.gensalt(this.strength);
            }
        } else {
            salt = BCrypt.gensalt();
        }

        return BCrypt.hashpw(rawPassword.toString(), salt);
    }

    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        if(encodedPassword != null && encodedPassword.length() != 0) {
            if(!this.BCRYPT_PATTERN.matcher(encodedPassword).matches()) {
                log.warn("Encoded password does not look like BCrypt");
                return false;
            } else {
                return BCrypt.checkpw(rawPassword.toString(), encodedPassword);
            }
        } else {
            log.warn("Empty encoded password");
            return false;
        }
    }

    public static void main(String[] args){
        BCryptPasswordEncoder bcrypt=new BCryptPasswordEncoder();//实例化BCryptPasswordEncoder加密类
        String encryptPassword=bcrypt.encode("123456");//加密完的密码
        String encryptPassword1=bcrypt.encode("6112ed5f-9592-4d91-82a9-745b88c59fba");//加密完的密码
        String encryptPassword2=bcrypt.encode("f63f451b-a2e3-4387-863e-fe6c5d315eb2");//加密完的密码
        boolean flag = bcrypt.matches("111111","$2a$10$TuxnyLaj/LieKw8y4pKxy.5kfHue.AjDLXXAhRTDlnSxcYPt8TlYW");
        System.out.println(encryptPassword);
        System.out.println(encryptPassword1);
        System.out.println(encryptPassword2);
        System.out.println(flag);
    }
}
